package edu.nf.project.services.employeeAndCustomerInformation.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import edu.nf.project.entitys.entity.other.dto.StaffInfoDTO;
import edu.nf.project.entitys.entity.accountsAndPermissions.convention.Users;
import edu.nf.project.entitys.entity.employeeAndCustomerInformation.convention.StaffInfo;
import edu.nf.project.entitys.enums.employeeAndCustomerInformation.StaffStatusEnum;
import edu.nf.project.mappers.accountsAndPermissions.convention.UsersMapper;
import edu.nf.project.mappers.employeeAndCustomerInformation.convention.StaffInfoMapper;
import edu.nf.project.services.employeeAndCustomerInformation.StaffInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 员工信息 Service 实现类
 */
@Service
public class StaffInfoServiceImpl implements StaffInfoService {
    @Autowired
    private StaffInfoMapper staffInfoMapper;
    
    @Autowired
    private UsersMapper usersMapper;

    @Override
    public Page<StaffInfoDTO> getStaffList(Page<StaffInfoDTO> page, String staffName, String phone) {
        // 使用自定义的关联查询方法
        return staffInfoMapper.selectStaffListWithUser(page, staffName);
    }

    @Override
    public StaffInfo getStaffInfo(Integer staffId) {
        return staffInfoMapper.selectById(staffId);
    }

    @Override
    @Transactional
    public boolean updateStaff(StaffInfo staffInfo) {
        // 更新数据
        return staffInfoMapper.updateById(staffInfo) > 0;
    }

    @Override
    @Transactional
    public boolean assignAccount(Integer uId) {
        // 查询用户是否存在
        Users user = usersMapper.selectById(uId);
        if (user == null) {
            return false;
        }
        // 检查用户是否已经被分配为员工
        LambdaQueryWrapper<StaffInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StaffInfo::getUId, uId);
        StaffInfo existingStaff = staffInfoMapper.selectOne(queryWrapper);
        if (existingStaff != null) {
            return false;
        }
        // 创建新员工
        StaffInfo staffInfo = new StaffInfo();
        staffInfo.setUId(uId);
        staffInfo.setStaffFullname(user.getUName());
        staffInfo.setStaffStatus(StaffStatusEnum.INCUMBENCY);
        return staffInfoMapper.insert(staffInfo) > 0;
    }
} 